//
//  RegisterViewController.m
//  QA
//
//  Created by 李小龙 on 2017/5/2.
//  Copyright © 2017年 ZDQK. All rights reserved.
//

#import "RegisterViewController.h"
#import "RuleViewController.h"
#import <YBAttributeTextTapAction/UILabel+YBAttributeTextTapAction.h>
#import "L&RViewModel.h"


@interface RegisterViewController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *phoneNumBackView;
@property (weak, nonatomic) IBOutlet UITextField *phoneNumTF;
@property (weak, nonatomic) IBOutlet UIView *verificationBackView;
@property (weak, nonatomic) IBOutlet UITextField *verificationTF;
@property (weak, nonatomic) IBOutlet UIView *passwordBackView;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UIView *passwordAgainBackView;
@property (weak, nonatomic) IBOutlet UITextField *passwordAgainTF;

@property (weak, nonatomic) IBOutlet UIButton *verificationButton;
@property (weak, nonatomic) IBOutlet UIButton *registerButton;
@property (weak, nonatomic) IBOutlet UIButton *ruleButton;
@property (weak, nonatomic) IBOutlet UIButton *selectRuleButton;
@property (weak, nonatomic) IBOutlet UILabel *ruleLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *registerTopLayout;

@property(strong,nonatomic) L_RViewModel  *LoginViewModel;


@property (nonatomic, strong) NSTimer *myTimer;
@property (nonatomic, assign) NSInteger num;    // 倒计时60秒

@end

@implementation RegisterViewController
#pragma mark - IBAction
#pragma mark 返回
- (IBAction)backButtonAction:(id)sender {
    [self disMissSelf];
}

#pragma mark 注册
- (IBAction)registerButtonAction:(id)sender {
    if (![LXLIsPhoneNumber valiMobile:_phoneNumTF.text]) {
        [self showAlertMessage:@"请输入正确的手机号"];
        return;
    }
    if (!TextIsNotNil(_verificationTF.text)) {
        [self showAlertMessage:@"请输入验证码"];
        return;
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (!TextIsNotNil(_thirdStr)) {
        if (!TextIsNotNil(_passwordTF.text) || _passwordTF.text.length < 6 || _passwordTF.text.length > 16) {
            [self showAlertMessage:@"请输入密码，密码为6~16位的英文加数字"];
            return;
        }
        if (![_passwordTF.text isEqualToString:_passwordAgainTF.text]) {
            [self showAlertMessage:@"两次输入的密码不一致"];
            return;
        }
        [dic setObject:_passwordTF.text       forKey:@"mpass"];
        [dic setObject:_passwordAgainTF.text  forKey:@"qrpass"];
    } else {
        [dic setObject:self.thirdOpenID forKey:@"mwechatid"];
    }
  
    
    [self.view endEditing:YES];
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [dic setObject:_verificationTF.text       forKey:@"verificationcode"];
    [dic setObject:_phoneNumTF.text           forKey:@"mtel"];
    
    NSString *url;
    switch (self.type) {
        case typeRegister:
            url = URL_Regist;
            break;
        case typePassword: case typePasswordChange:
            url = URL_Forgotpwd;
            break;
        case typeThirdWechat:
            url = URL_Regist_Wechat;
        default:
            break;
    }
    
    __weak typeof(self) weakSelf = self;
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dics = responseObject;
        NSString *codes = [dics objectForKey:@"code"];
        if ([codes isEqualToString:@"200"]) {
            UserModel *model = [UserModel mj_objectWithKeyValues:dics[@"data"]];
            [UserInfo shareInstance].user = model;
            [[UserInfo shareInstance] updateUserModel];
            
            if (weakSelf.type == typePassword || weakSelf.type == typePasswordChange) {
                // 忘记密码|修改密码
                [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"修改成功" animated:YES];
                [weakSelf disMissSelf];
            } else {
                // 注册
                NSLog(@"注册成功");
                [UserInfo shareInstance].isLogin = YES;
                [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                    [JPUSHService setAlias:[UserInfo shareInstance].user.mid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                        
                    } seq:[UserInfo shareInstance].user.mid.integerValue];
                    //登录跳到主页面
                    //注册成功
                    [weakSelf.navigationController dismissViewControllerAnimated:YES completion:nil];
//                    [weakSelf.navigationController popToRootViewControllerAnimated:YES];
                }];
                
                [[NSUserDefaults standardUserDefaults] setObject:self.phoneNumTF.text forKey:PhoneNumber];
                
            }
            
        } else {
            [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:codes animated:YES];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:weakSelf.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark 获取验证码
- (IBAction)verificationButtonAction:(id)sender {
    if ([LXLIsPhoneNumber valiMobile:_phoneNumTF.text]) {
        _verificationButton.userInteractionEnabled = NO;
        
        self.myTimer =  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [_verificationButton setCircleWithColor:[UIColor grayTextColor] borderWidth:1.0 cornerRadius:2.0];
        __weak typeof(self) weakSelf = self;
        [MBProgressHUD showHUDProgress:self.view animated:YES];
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setObject:_phoneNumTF.text forKey:@"mobile"];
        //获取验证码接口
        [MYAFNetworking POST:URL_SMS parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSDictionary *dics = responseObject;
            NSString *codes = [dics objectForKey:@"code"];
            if ([codes isEqualToString:@"200"]) {
                
            } else {
                [MBProgressHUD showError:weakSelf.view title:[dics safeObjectForKey:@"message"] code:codes animated:YES];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
        
    } else {
        [self showAlertMessage:@"请输入正确的手机号"];
    }
}

- (IBAction)checkRuleButtonAction:(id)sender {
    RuleViewController *ruleVC = [[RuleViewController alloc] init];
    ruleVC.title = @"服务协议";
    ruleVC.cid = @"3";
    [self.navigationController pushViewController:ruleVC animated:YES];
}
- (IBAction)selectRuleButtonAction:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setSelected:!button.selected];
    if (button.selected) {
        [self.registerButton setBackgroundColor:[UIColor yellowTextColor]];
    } else {
        [self.registerButton setBackgroundColor:[UIColor grayBackgroundColor]];
    }
}

#pragma mark -
- (void)viewDidLoad {
    [super viewDidLoad];
    self.LoginViewModel = [[L_RViewModel alloc]init];
    [self bindModel];
    [self updateBackView];
    [self updateView];
    self.num = 60;
}

-(void)bindModel{
    RAC(self.LoginViewModel,userName) = self.phoneNumTF.rac_textSignal;
    RAC(self.LoginViewModel,password) = self.passwordTF.rac_textSignal;
    RAC(self.LoginViewModel,password_Again) = self.passwordAgainTF.rac_textSignal;
    RAC(self.LoginViewModel,codeNum) = self.verificationTF.rac_textSignal;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;

}

- (void)updateBackView {
    __weak typeof(self)weakSelf = self;
    RACSignal *LoginBtnEnableSignal = [self.LoginViewModel registerBtnIsValid];
    [LoginBtnEnableSignal subscribeNext:^(id  _Nullable x) {
        NSNumber *number = [NSNumber numberWithInt:0];
        if ([number isEqual:x]) {
            [weakSelf.registerButton setBackgroundColor:[UIColor colorWithHex:0xDDDDDD alpha:1]];
            weakSelf.registerButton.enabled = NO;
        }else{
            weakSelf.registerButton.enabled = YES;
            [weakSelf.registerButton setBackgroundColor:[UIColor yellowTextColor]];
        }
    }];
    
    RACSignal *CodeBtnEnableSignal = [self.LoginViewModel getCodeBtnIsValid];
    [CodeBtnEnableSignal subscribeNext:^(id  _Nullable x) {
        NSNumber *number = [NSNumber numberWithInt:0];
        if ([number isEqual:x]) {
           [self.verificationButton setCircleWithColor:[UIColor whiteColor] borderWidth:1.0 cornerRadius:2.0];
            weakSelf.verificationButton.enabled = NO;
        }else{
            weakSelf.verificationButton.enabled = YES;
            [self.verificationButton setCircleWithColor:[UIColor yellowTextColor] borderWidth:1.0 cornerRadius:2.0];
        }
    }];
    
    self.ruleLabel.enabledTapEffect = NO;
    [self.ruleLabel yb_addAttributeTapActionWithStrings:@[@"用户协议",@"隐私政策"] tapClicked:^(NSString *string, NSRange range, NSInteger index) {
        switch (index) {
            case 0:
            {
                RuleViewController *ruleVC = [[RuleViewController alloc] init];
                ruleVC.title = @"用户协议";
                ruleVC.cid = @"3";
                [self.navigationController pushViewController:ruleVC animated:YES];
            } break;
            case 1:
            {
                RuleViewController *ruleVC = [[RuleViewController alloc] init];
                ruleVC.title = @"隐私政策";
                ruleVC.cid = @"4";
                [self.navigationController pushViewController:ruleVC animated:YES];
            } break;
            default:
                break;
        }
        
    }];
    
    
}

- (void)updateView {
    // 忘记密码 修改密码
    if (self.type == typePassword || self.type == typePasswordChange) {
        self.type == typePassword ? [self.registerButton setTitle:@"找回密码" forState:UIControlStateNormal]:[self.registerButton setTitle:@"修改密码" forState:UIControlStateNormal];
        
        [self.passwordTF setPlaceholder:@"请输入新密码"];
        [self.passwordAgainTF setPlaceholder:@"请再次输入新密码"];
        [self.registerButton setBackgroundColor:[UIColor yellowTextColor]];
    }
    // 注册
    if (self.type == typeRegister) {
        
        
    }
    // 微信注册
    if (self.type == typeThirdWechat) {
        [self.passwordBackView setHidden:YES];
        [self.passwordAgainBackView setHidden:YES];
        
        [self.registerButton setTitle:@"确定" forState:UIControlStateNormal];
        self.registerTopLayout.constant -= 110;
    }
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self.scrollView addGestureRecognizer:tap];
}

#pragma mark --键盘消失
- (void)tap:(UITapGestureRecognizer *)tapGes{
    [self.view endEditing:YES];
}

#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if ([string isEqualToString:@""]) {
        return YES;
    }
    
    if ([string isEqualToString:@" "]) {
        return NO;
    }
    if (textField.tag == 1000) {// 手机号
        if (textField.text.length >= 11) {
            return NO;
        } else {
            return YES;
        }
    } else if(textField.tag == 1001) {// 验证码
        if (textField.text.length >= 4) {
            return NO;
        }else{
            return YES;
        }
    } else if (textField.tag == 1002 || textField.tag == 1003) {// 两次密码输入
        
        if (textField.text.length >= 16 || [string isNumAndChar] == NO) {
            return NO;
        } else {
            return YES;
        }
    } else
        return YES;
}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [super touchesEnded:touches withEvent:event];
    [self.view endEditing:YES];
}

- (void)timerAction{
    [_verificationButton setTitle:[NSString stringWithFormat:@"%lds",(long)self.num --] forState:UIControlStateNormal];
    if (_num == 0) {
        [self stopTimer];
    }
}
- (void)stopTimer {
    [_verificationButton setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
    _verificationButton.userInteractionEnabled = YES;
    [_verificationButton setTitleColor:[UIColor yellowTextColor] forState:UIControlStateNormal];
    [_verificationButton setCircleWithColor:[UIColor yellowTextColor] borderWidth:1.0 cornerRadius:2.0];
    _num = 60;
    [_myTimer invalidate];
}
- (void)dealloc {
    [self.myTimer invalidate];
    self.myTimer = nil;
}
@end
